package com.joker.airoleplayplatformback.controller;

import com.joker.airoleplayplatformback.domain.dto.LoginRequestDTO;
import com.joker.airoleplayplatformback.domain.vo.RegisterRequestVO;
import com.joker.airoleplayplatformback.domain.entity.R;
import com.joker.airoleplayplatformback.domain.po.UserPO;
import com.joker.airoleplayplatformback.service.UserService;
import com.joker.airoleplayplatformback.utils.JwtUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 用户认证控制器
 *
 * @author feixiang.li
 * @since 2025-09-27
 */
@Slf4j
@RestController
@RequestMapping("/api/auth")
@Tag(name = "用户认证", description = "用户登录注册相关接口")
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public R<Map<String, Object>> register(@RequestBody RegisterRequestVO request) {
        try {
            UserPO user = userService.register(
                    request.getUsername(),
                    request.getPassword(),
                    request.getNickname(),
                    request.getEmail()
            );

            // 注册成功后直接登录
            String token = jwtUtils.generateToken(user.getId(), user.getUsername(), user.getNickname());

            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("user", Map.of(
                    "id", user.getId(),
                    "username", user.getUsername(),
                    "nickname", user.getNickname(),
                    "email", Objects.isNull(user.getEmail())? "" : user.getEmail()
            ));

            return R.ok(result);
        } catch (Exception e) {
            log.error("用户注册失败", e);
            return R.error(500, "注册失败: " + e.getMessage());
        }
    }

    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public R<Map<String, Object>> login(@RequestBody LoginRequestDTO request) {
        try {
            String token = userService.login(request.getUsername(), request.getPassword());

            // 获取用户信息
            UserPO user = userService.findByUsername(request.getUsername());

            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("user", Map.of(
                    "id", user.getId(),
                    "username", user.getUsername(),
                    "nickname", user.getNickname(),
                    "email", user.getEmail() != null ? user.getEmail() : ""
            ));

            return R.ok(result);
        } catch (Exception e) {
            log.error("用户登录失败", e);
            return R.error(500, "登录失败: " + e.getMessage());
        }
    }

    @GetMapping("/profile")
    @Operation(summary = "获取用户信息")
    public R<Map<String, Object>> getProfile(@RequestHeader("Authorization") String token) {
        try {
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }

            Long userId = jwtUtils.getUserIdFromToken(token);
            UserPO user = userService.findById(userId);

            if (user == null) {
                return R.error(500, "用户不存在");
            }

            Map<String, Object> result = Map.of(
                    "id", user.getId(),
                    "username", user.getUsername(),
                    "nickname", user.getNickname(),
                    "email", user.getEmail() != null ? user.getEmail() : "",
                    "avatarUrl", user.getAvatarUrl() != null ? user.getAvatarUrl() : ""
            );

            return R.ok(result);
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return R.error(500, "获取用户信息失败: " + e.getMessage());
        }
    }

    @PostMapping("/refresh")
    @Operation(summary = "刷新Token")
    public R<Map<String, String>> refreshToken(@RequestHeader("Authorization") String token) {
        try {
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }

            String newToken = jwtUtils.refreshToken(token);
            if (newToken == null) {
                return R.error(500, "Token刷新失败");
            }

            Map<String, String> result = Map.of("token", newToken);
            return R.ok(result);
        } catch (Exception e) {
            log.error("Token刷新失败", e);
            return R.error(500, "Token刷新失败: " + e.getMessage());
        }
    }



}
